# Auther：wujehy
# email:wujehy@qq.com
# @File : SDK.py 
# @Time : 19-3-25 下午9:56

"""
这个类是开发工具包

用于接入　服务器后端的
    前置条件　使用　requests 模块　
"""
import base64
import json
from binascii import b2a_hex, a2b_hex

import requests
from Crypto.Cipher import AES
class SDK():
    # 存储　openid
    openid=''
    username=''
    password=''
    session=''
    host=''
    def __init__(self):
        # 初始化　网络工具
        self.session = requests.Session()
        self.session.verify = False
        self.session.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)Chrome/51.0.2704.103 Safari/537.36',
        }

        self.username="a"
        self.password="dada"
        self.host='http://127.0.0.1:8000'
        return
    # 登录操作　获取opneid
    def Login(self):
        """
        登录操作　
            openid　是　当前唯一标识
            没有openid 是　不能做任何操作
        :return:　返回　openid
        """
        url=self.host+'/login'
        datas = {
            "user": self.username,
            "password": self.password,
            "csrfmiddlewaretoken":self.getCsrf()
        }
        req = self.session.post(url=url, data=datas)
        return req.text

    #
    def addDevice(self,pid,types,data):
        url = self.host + "/adddevice"
        datas = {
            "openid": openid,
            "pid": pid,
            "types": types,
            "data": data,
            "csrfmiddlewaretoken": self.getCsrf()
        }
        req = self.session.post(url=url, data=datas)
        return req.json()

    # def addDevice(self,pid,did):
    #     return

    def myDevices(self,openid,pid):
        url = self.host + "/findAllDevice"
        datas = {
            "openid": openid,
            "pid": pid,
            "csrfmiddlewaretoken": self.getCsrf()
        }
        req = self.session.post(url=url, data=datas)
        return req.json()
    def CreatProject(self,openid,title,description,type,note=None):
        url=self.host+"/addproject"
        datas={
            "openid":openid,
            "title":title,
            "description":description,
            "type":type,
            "note":note,
            "csrfmiddlewaretoken": self.getCsrf()
        }
        req = self.session.post(url=url, data=datas)
        return req.json()
    # def uploadTest(self,):
    #     dregister = None, openid = None, types = None, panid = None, serial = None, data = None
    #
    def uploadData(self, dregister=None, openid=None, types=None, panid=None, serial=None, data=None):
        """
        上传数据到服务器

        :param dregister:　设备注册的唯一　ｉd
        :param openid: 登录的　openid
        :param types: 节点终端类型
        :param panid: 节点penid 也就是　个域网　编号
        :param serial: 个域网中子节点　的序列号
        :param data: 上传的具体数据 json　格式
        :return: 上传成功返回ｓｕｃｃｅｓｓ + 说明　否则　error　＋说明
        """
        # 数据信息
        datas={
            "dregister":dregister,
            "openid":openid,
            "type":types,
            "panid":panid,
            "serial":serial,
            "data":data,
            "csrfmiddlewaretoken": self.getCsrf()
        }
        url=self.host+'/upload'
        req=self.session.post(url=url,data=datas)
        return req

    # 登录验证器
    def getCsrf(self):
        """
        获取验证信息
        :return:
        """
        url=self.host+'/csrf'
        return self.session.get(url=url).text

    # 加密器
    def AES_encode(self,key,codes,encoding='utf-8'):
        aes = AES.new(self.code2Hex(key), AES.MODE_ECB).encrypt(self.code2Hex(codes))
        return str(base64.encodebytes(aes),encoding=encoding)

    # 解密器
    def AES_decode(self,key,codes,encoding='utf-8'):
        aes=AES.new(self.code2Hex(key),AES.MODE_ECB)
        return str(aes.decrypt(base64.decodebytes(codes.encode(encoding=encoding))),encoding=encoding).replace("\x00",'')

    # 加密工具字符处理
    def code2Hex(self,value):
        while len(value) % 16 != 0:
            value += '\0'
        return str.encode(value)  # 返回bytes

if __name__=="__main__":


    # basr64e=str(base64.encodebytes(end),)
    # print(basr64e)
    # dec=str(aes.decrypt(end),encoding='utf-8')
    # print(dec.replace('\x00',''))
    # # strt='sdadad\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
    # # print(strt.replace('\x00',''))
    # Test="dadda"
    # key="aaa"
    # T=SDK()
    # t1=T.AES_encode(key,Test)
    # print(t1)
    #
    # t2=T.AES_decode(key,t1)
    #
    # print(t2)
    T=SDK()
    openid="9779ac64a562cf9f6dc0e55a705d7658"
    # print(T.Login().text)
    # print(T.CreatProject(openid,"adad","adad","M","ada"))
    data={
        "dda":"dada",
        "dad":"dda"
    }
    # print(T.addDevice(3,types="dad",data=json.dumps( data)))
    print(T.myDevices(openid=openid,pid=3))

    # data={'error': 'success', 'data': {'Pid': '3', 'Devices': [{'Dregister': '578aea14857ee64bba27e823e9d93dac', 'Dtype': 'dad', 'Ddata': '{"dad": "dda", "dda": "dada"}', 'Dstatus': 0, 'PDdatetime': '2019-03-26 22:26:54'}]}}
    # jsons=json.dumps(data)
    # print(jsons)